﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;

namespace Z.Nlayer.Utility
{
    public static class LoggerHelper
    {
        private const string DirectPath = "Log";
        private const string BrStr = "---------------------------------------------------------------------------";
        private static Queue<string> ListQueue = new Queue<string>();
        public static void Log(string msg)
        {
            ListQueue.Enqueue(msg);
        }

        public static void UseLocalLog(this IServiceCollection services)
        {
            Writelog("项目启动!");
            Task.Run(() =>
            {
                while (true)
                {
                    if (ListQueue.Count > 0)
                    {
                        var errMessage = ListQueue.Dequeue();
                        Writelog(errMessage);
                    }
                    else
                    {
                        Thread.Sleep(3000);
                    }
                }
            });
        }
        static void Writelog(string msg)
        {
            var dt = DateTime.Now;
            DirectoryInfo di = new DirectoryInfo(Directory.GetCurrentDirectory() + "/" + DirectPath);
            if (di.Exists == false) di.Create();
            DirectoryInfo disub = new DirectoryInfo(di.ToString() + "/" + dt.ToString("yyyy-MM"));
            if (disub.Exists == false) disub.Create();
            var FilePath = disub.ToString() + "/" + dt.ToString("yyyy-MM-dd") + ".txt";
            if (!File.Exists(FilePath))
            {
                using (var fs = File.Create(FilePath)) 
                {
                    fs.Flush();
                }
            }
            using (
                var filestream = new System.IO.FileStream(FilePath, System.IO.FileMode.Append,
                    System.IO.FileAccess.Write, FileShare.ReadWrite))
            {
                Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
                using (var sw = new StreamWriter(filestream, Encoding.GetEncoding("gb2312")))
                {
                    sw.WriteLine("[" + dt.ToString("yyyy-MM-dd HH:mm:ss") + "]");
                    sw.WriteLine(msg);
                    sw.WriteLine(BrStr);
                    sw.Flush();
                }
            }
        }
    }
}
